package com.haixiaoke.saas.manage.user.controller;

import cn.hutool.core.util.ObjectUtil;
import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.StringUtils;
import com.haixiaoke.saas.common.utils.poi.ExcelUtil;
import com.haixiaoke.saas.department.service.ITenantService;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.user.domain.BizTenantUser;
import com.haixiaoke.saas.user.domain.BizUserBusiness;
import com.haixiaoke.saas.system.framework.security.util.SecurityUtils;
import com.haixiaoke.saas.user.domain.BizUserRole;
import com.haixiaoke.saas.user.service.IBizTenantUserService;
import com.haixiaoke.saas.user.service.IBizUserBusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author panda
 * @Date 2023/12/22
 **/
@RestController
@RequestMapping("/manage/user/userBusiness")
public class ManageBizUserBusinessController extends BaseController {

    @Autowired
    private IBizUserBusinessService iBizUserBusinessService;
    @Autowired
    private ITenantService iTenantService;
    @Autowired
    private IBizTenantUserService iBizTenantUserService;

    /**
     * 查询某个机构下的用户列表
     */
    @PreAuthorize("@ss.hasPermi('manage:user:list')")
    @GetMapping("/pageByDep")
    public TableDataInfo pageByDep(BizUserBusiness user) {
        if (StringUtils.isBlank(user.getTenantId())) {
            throw new ServiceException("缺少机构标识");
        }
        startPage();
        List<BizUserBusiness> list = iBizUserBusinessService.selectUserBusListByDep(user);
        return getDataTable(list);
    }

    /**
     * 查询用户列表
     */
    @PreAuthorize("@ss.hasPermi('manage:user:list')")
    @GetMapping("/pageByDepUser")
    public TableDataInfo pageByDepUser(BizUserBusiness user) {
        startPage();
        List<BizUserBusiness> list = iBizUserBusinessService.selectUserBusListByDepUser(user);
        return getDataTable(list);
    }

    /**
     * 查询用户列表
     */
    @GetMapping("/list")
    public AjaxResult list(BizUserBusiness user) {
        if (StringUtils.isBlank(user.getTenantId())) {
            return error("缺少机构标识");
        }
        List<BizUserBusiness> list = iBizUserBusinessService.selectUserBusListByDep(user);
        return success(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('manage:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizUserBusiness user) {
        List<BizUserBusiness> list = iBizUserBusinessService.selectBizUserBusinessList(user);
        ExcelUtil<BizUserBusiness> util = new ExcelUtil<BizUserBusiness>(BizUserBusiness.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('manage:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<BizUserBusiness> util = new ExcelUtil<BizUserBusiness>(BizUserBusiness.class);
        List<BizUserBusiness> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = iBizUserBusinessService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<BizUserBusiness> util = new ExcelUtil<BizUserBusiness>(BizUserBusiness.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 添加用户
     * @param user 用户
     * @return
     */
    @PreAuthorize("@ss.hasPermi('manage:userBusiness:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody BizUserBusiness user) {
        if (!iBizUserBusinessService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，账号名称已存在");
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !iBizUserBusinessService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isBlank(user.getTenantId())){
            return error("机构数据异常");
        }
        if (StringUtils.isNull(user.getRoleId())){
            return error("角色数据异常");
        }
        if (iTenantService.checkPopulation(user.getTenantId())){
            return error("该企业已达到最大人数");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        user.setActivateStatus(BizUserBusiness.ACTIVATE_STATUS_NOT_ACTIVATED);
        return toAjax(iBizUserBusinessService.insertBizUserBusiness(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('manage:userBusiness:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody BizUserBusiness user) {
        //iBizUserBusinessService.checkUserDataScope(user.getUserId());
        if (!user.getTenantId().equals(user.getOldTenantId()) && iBizTenantUserService.selectBizDepartmentUserByUserIdAndDepId(user.getUserId(),user.getTenantId()) >0) {
            return error("该用户已存在于该机构！");
        }
        if (!iBizUserBusinessService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，账号名称已存在");
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !iBizUserBusinessService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isBlank(user.getTenantId())){
            return error("机构数据异常");
        }
        if (StringUtils.isNull(user.getRoleId())){
            return error("角色数据异常");
        }
        user.setUpdateBy(getUsername());
        user.setPassword(null);
        return toAjax(iBizUserBusinessService.updateBizUserBusiness(user));
    }

    /**
     * 修改用户密码
     */
    @PreAuthorize("@ss.hasPermi('manage:userBusiness:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePassword")
    public AjaxResult editPassword(@Validated @RequestBody BizUserBusiness user) {
        user.setUpdateBy(getUsername());
        return toAjax(iBizUserBusinessService.updateBizUserPassword(user));
    }

    /**
     * 删除用户下某个机构与用户的关联数据
     * @param depUser
     * @return
     */
    @PreAuthorize("@ss.hasPermi('manage:userBusiness:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/byDep")
    public AjaxResult remove(@RequestBody BizTenantUser depUser) {
        return toAjax(iBizUserBusinessService.deleteBizUserBusinessByUserId(depUser));
    }

    /**
     * 获取用户详细信息
     */
    @GetMapping
    public AjaxResult changeStatus(BizUserRole userRole) {
        return success(iBizUserBusinessService.selectBizUserBusinessByUserId(userRole.getUserId(),userRole.getTenantId()));
    }

    @GetMapping("/checkUser/{phonenumber}")
    public AjaxResult checkUser(@PathVariable String phonenumber){
        return iBizUserBusinessService.checkUser(phonenumber);
    }

}
